<template>
  <div class="login-container">
    <h1>登录</h1>
    <form @submit.prevent="handleSubmit">
      <div>
        <label for="phone">手机号:</label>
        <input type="text" id="phone" v-model="state.loginForm.phone"/>
      </div>
      <div>
        <label for="code">验证码:</label>
        <input type="text" id="code" v-model="state.loginForm.code"/>
      </div>
      <button type="button" @click="getCode" :disabled="state.isButtonDisabled">{{ state.buttonLabel }}
      </button>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script setup lang="ts">
import {useRouter} from 'vue-router';
import {Md5} from "ts-md5";
import {signGengw} from "~/composables/md5";
import {userLoginStore} from "~/stores/userLogin";
const router = useRouter(); // 获取路由实例
const userLogin = userLoginStore()
const state = reactive({
  loginForm: {
    phone: '',
    code: ''
  },
  isButtonDisabled: false,
  buttonLabel: '获取验证码',
  countdown: 0,
  timer: null as any
});
function startCountdown() {
  state.isButtonDisabled = true;
  state.timer = setInterval(() => {
    state.countdown--;
    state.buttonLabel = `${state.countdown}秒后重新获取`;
    if (state.countdown <= 0) {
      clearInterval(state.timer);
      state.isButtonDisabled = false;
      state.buttonLabel = '获取验证码';
      localStorage.removeItem('countdownEndTime');
    }
  }, 1000);
}

function getCode() {
  if (!state.loginForm.phone) {
    toast.error('请输入手机号');
    return;
  }
  const phoneRegex = /^1[3-9]\d{9}$/; // 简单的手机号校验正则
  if (!phoneRegex.test(state.loginForm.phone)) {
    toast.error('手机号格式不正确');
    return;
  }
  state.countdown = 60;
  localStorage.setItem('countdownEndTime', (Date.now() + state.countdown * 1000).toString());
  startCountdown();
  http.post('/api/login/sendCode', signGengw({mobile: state.loginForm.phone}));
}
function handleSubmit() {
  if (state.loginForm.code === '') {
    toast.error('验证码为空');
    return;
  }
  if (state.loginForm.code.length !== 4) {
    toast.error('验证码长度不正确');
    return;
  }

	http.post(`api/login/mobileLogin`,  signGengw({
		mobile: state.loginForm.phone,
		code: state.loginForm.code
	})).then((res: any) => {
    if (res.code == 200) {
      toast.success('登录成功！');
      const md5: any = new Md5()
      md5.appendAsciiStr(res.data.cellPhone);
      const sign = md5.end()
			userLogin.isLogin = true
			userLogin.token = sign
      router.push('/');
    }
  });
}

onMounted(() => {
  const countdownEndTime = localStorage.getItem('countdownEndTime');
  if (countdownEndTime) {
    const remainingTime = parseInt(countdownEndTime) - Date.now();
    if (remainingTime > 0) {
      state.countdown = Math.ceil(remainingTime / 1000);
      startCountdown();
    } else {
      localStorage.removeItem('countdownEndTime');
    }
  }
});

onBeforeUnmount(() => {
  if (state.timer) {
    clearInterval(state.timer);
  }
});
</script>

<style>
.login-container {
  max-width: 400px;
  margin: auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.login-container h1 {
  text-align: center;
}

.login-container form {
  display: flex;
  flex-direction: column;
}

.login-container form div {
  margin-bottom: 15px;
}

.login-container form label {
  display: block;
  margin-bottom: 5px;
}

.login-container form input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}

.login-container form button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.login-container form button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
<route lang="json">
{
"meta": {
"title": "login",
"layout": "notFound"
}
}
</route>
